package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.Coupon;
import com.wsd.smartcarwasher.domain.UserCoupon;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Api(tags = "用户优惠券相关接口")
@Controller
@CrossOrigin
public class UserCouponController {
    private static final Logger logger = LoggerFactory.getLogger(UserCouponController.class);

    @Resource
    private UserCouponService userCouponService;

    @Resource
    private WxService wxService;

    @Resource
    private CouponService couponService;

    @Resource
    private SMSService smsService;

    @Resource
    private UserInfoService userInfoService;

    /*@ApiOperation(value="添加优惠券给用户", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "userCoupon", value = "绑定了用户的优惠券信息", required = true, dataType = "UserCoupon")
    @RequestMapping(value = "/v1/add_user_coupon", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addUserCoupon(@RequestBody UserCoupon userCoupon) {

        int changeRows = userCouponService.addUserCoupon(userCoupon);
        if (changeRows == 0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(), userCoupon);
    }*/
    @Log("领取了活动优惠卷")
    @ApiOperation(value="根据优惠卷id添加优惠券给用户", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/v1/add_user_coupon/couponId", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addUserCoupon(@RequestParam(value = "userId",required = false) String userId,
                                  @RequestParam("couponId") int couponId,
                                  HttpServletRequest request) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        //2021.4.2 16:49  yangtap  前端传递的userId为空
        userId=user.getUserId();
        Coupon coupon = couponService.getCouponByCouponId(couponId);
        UserCoupon userCoupon = userCouponService.getUserCouponByIdAndUserId(couponId,userId);

        if (userCoupon != null) {
            return ReturnUtil.Error("已经领取过了！");
        }

        if (coupon == null) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }
        if(coupon.getEndTime()!= null &&coupon.getEndTime().before(new Date())){
            return ReturnUtil.Error("优惠卷已经过期！");
        }

        userCoupon = userCouponService.getValidUserCouponByCouponId(couponId);

        if (userCoupon == null) {
            return ReturnUtil.Error("已经领完了");
        }

        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        if (coupon.getValidDate() < 0) {
            userCoupon.setEndTime(null);
        } else if(coupon.getValidDate()>0){
            userCoupon.setEndTime(DateUtil.getDateLater(addTime, coupon.getValidDate()));
        }else if(coupon.getStartTime()!=null && coupon.getEndTime()!=null){
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setStartTime(coupon.getStartTime());
        }
        userCoupon.setUserId(userId);
        int rows = userCouponService.bindUserCouponByCode(userCoupon);
        if (rows<0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(),userCoupon);
    }


    @Log("用户通过二维码领取了活动优惠卷")
    @ApiOperation(value="根据优惠卷id添加优惠券给用户", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
//    @ApiImplicitParams({
////            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "couponId", value = "优惠券id", required = true, dataType = "Integer")
//    })
    @RequestMapping(value = "/v1/add_user_coupon/wx_code_couponId", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addUserCoupon(HttpServletRequest request,
                                  @RequestParam("couponId") int couponId) {

        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
//      UserInfo user=userInfoService.findByMobile("17791961563");
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        Coupon coupon = couponService.getCouponByCouponId(couponId);
        UserCoupon userCoupon = userCouponService.getUserCouponByIdAndUserId(couponId,user.getUserId());
        if (userCoupon != null) {
            return ReturnUtil.Error("已经领取过了！");
        }
        if (coupon == null) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }
        if(coupon.getEndTime()!= null &&coupon.getEndTime().before(new Date())){
            return ReturnUtil.Error("优惠卷已经过期！");
        }
        userCoupon = userCouponService.getValidUserCouponByCouponId(couponId);
        if (userCoupon == null) {
            return ReturnUtil.Error("已经领完了");
        }
        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        if (coupon.getValidDate() < 0) {
            userCoupon.setEndTime(null);
        } else if(coupon.getValidDate()>0){
            userCoupon.setEndTime(DateUtil.getDateLater(addTime, coupon.getValidDate()));
        }else if(coupon.getStartTime()!=null && coupon.getEndTime()!=null){
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setStartTime(coupon.getStartTime());
        }
        userCoupon.setUserId(user.getUserId());
        int rows = userCouponService.bindUserCouponByCode(userCoupon);
        if (rows<0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(),userCoupon);
    }





    @Log("发放了优惠卷")
    @ApiOperation(value="根据用户惠卷id添加优惠券给用户", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/add_user_coupon/userCouponId", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addUserCoupon(@RequestParam("mobile") String mobile,
                                  @RequestParam("userCouponId") String userCouponId) {

        UserInfo user =   userInfoService.findByMobile(mobile);

        if(user==null){

            return ReturnUtil.Error("用户不存在！");
        }

        UserCoupon userCoupon = userCouponService.getUserCouponById(userCouponId);
        Coupon coupon = userCoupon.getCoupon();
        if (coupon == null) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }
        if(coupon.getEndTime()!= null &&coupon.getEndTime().before(new Date())){
            return ReturnUtil.Error("优惠卷已经过期！");
        }
        if (userCoupon == null) {
            return ReturnUtil.Error("不存在的优惠卷");
        }

        if (userCoupon.getUserId()!=null){
            return ReturnUtil.Error("优惠卷已经被领取！");
        }

        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        if (coupon.getValidDate() < 0) {
            userCoupon.setEndTime(null);
        } else if(coupon.getValidDate()>0){
            userCoupon.setEndTime(DateUtil.getDateLater(addTime, coupon.getValidDate()));
        }else if(coupon.getStartTime()!=null && coupon.getEndTime()!=null){
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setStartTime(coupon.getStartTime());
        }
        userCoupon.setUserId(user.getUserId());
        int rows = userCouponService.bindUserCouponByCode(userCoupon);
        if (rows<0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        //发送短息通知用户
        //UserInfo user =  userInfoService.findById(user.getUserId());
        if(null !=user && StringUtils.isNotBlank(user.getMobile())){
            smsService.sendCouponMSG(user.getMobile(),coupon.getCouponName(),DateUtil.format(userCoupon.getEndTime()));
        }

        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(),userCoupon);
    }


    @ApiOperation(value="小程序-查询用户名下的所有未使用的优惠券", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/all_user_coupons", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryAllUserCoupons(HttpServletRequest request) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), userCouponService.getAllUnusedUserCoupons(user.getUserId()));
    }


    //lyj
    @Log("兑换了优惠卷")
    @ApiOperation(value="小程序－根据优惠券码给用户添加优惠卷", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/add_user_coupon_by_code", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addUserCoupon(@RequestParam String couponCode,HttpServletRequest request ) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        UserCoupon userCoupon =  userCouponService.getCouponsByCode(couponCode);

        if (userCoupon == null){
            return ReturnUtil.Error("无效的优惠卷码！");
        }
        Coupon coupon=userCoupon.getCoupon();

        if (userCoupon.getUserId()!=null){
            return ReturnUtil.Error("优惠卷已经被领取！");
        }


        if(coupon.getEndTime()!= null &&coupon.getEndTime().after(new Date())){
            return ReturnUtil.Error("优惠卷已经过期！");
        }

        /*List<UserCoupon> ls =  userCouponService.getAllByCouponIdAndUserid(coupon.getCouponId(),user.getUserId());
        if (ls.size()>= coupon.getIsMultiple()){
            return ReturnUtil.Error("超出领取次数！");
        }*/

        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        if (coupon.getValidDate() < 0) {
            userCoupon.setEndTime(null);
        } else if(coupon.getValidDate()>0){
            userCoupon.setEndTime(DateUtil.getDateLater(addTime, coupon.getValidDate()));
        }else if(coupon.getStartTime()!=null && coupon.getEndTime()!=null){
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setStartTime(coupon.getStartTime());
        }
        userCoupon.setUserId(user.getUserId());
        int rows = userCouponService.bindUserCouponByCode(userCoupon);
        if (rows<0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(),userCoupon);
    }



    @ApiOperation(value="pc-查询用户名下的所有未使用的优惠券", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/pc/all_user_coupons", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryAllUserCouponsPC(@RequestParam String userId) {

        return ReturnUtil.Success(ResultState.QUERY_COUPON_SUCCESS.getMsg(), userCouponService.getAllUserCoupons(userId));
    }

    //lyj
    @ApiOperation(value="小程序－用户分享获得Ｂ类优惠卷", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "userId", value = "Ａ邀请了　Ｂ　此处传Ａ的用户ｉｄ　ａ的用户ｉｄ　在太阳码中", required = true, dataType = "String")
    @RequestMapping(value = "/v1/a_b_coupon", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap ABGetCoupon(@RequestParam String userId,HttpServletRequest request ) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
//            UserInfo user=this.userInfoService.findById("Cg6Z46MQif");
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        Coupon coupon = couponService.getCouponsByNewB();
        //给ａ加
        UserCoupon userCoupon = userCouponService.addUserCoupon(userId,coupon);
        if (null ==userCoupon) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        //给ｂ加
        userCoupon = userCouponService.addUserCoupon(user.getUserId(),coupon);
        if (null ==userCoupon) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg());
    }
    //===========================================


    @Log("删除了用户优惠卷")
    @ApiOperation(value="删除用户优惠卷", notes = "删除用户优惠卷", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/add_user_coupon/delete", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap delete(@RequestParam("userCouponId") String userCouponId) {
        //UserCoupon userCoupon = userCouponService.getUserCouponById(userCouponId);
        int rows = userCouponService.deleteByUserCouponId(userCouponId);
        if(rows<0){
            return ReturnUtil.Success("删除失败");
        }
        return ReturnUtil.Success("删除成功");
    }

}
